package com.talos.ums.service.user;

import com.talos.framework.common.pojo.PageResult;
import com.talos.framework.common.util.object.BeanUtils;
import com.talos.ums.controller.admin.user.vo.UmsUserPageReqVO;
import com.talos.ums.controller.admin.user.vo.UmsUserSaveReqVO;
import com.talos.ums.dal.dataobject.user.UmsUserDO;
import com.talos.ums.dal.mysql.user.UmsUserMapper;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;

import static com.talos.framework.common.exception.enums.GlobalErrorCodeConstants.DATA_NOT_FOUND;
import static com.talos.framework.common.exception.util.ServiceExceptionUtil.exception;

/**
 * 用户表 Service 实现类
 *
 * @author ${table.author}
 */
@Service
@Validated
public class UmsUserServiceImpl implements UmsUserService {

    @Resource
    private UmsUserMapper userMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long createUser(UmsUserSaveReqVO createReqVO) {
        // 插入
        UmsUserDO user = BeanUtils.toBean(createReqVO, UmsUserDO.class);
        userMapper.insert(user);
        // 返回
        return user.getId();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateUser(UmsUserSaveReqVO updateReqVO) {
        // 校验存在
        validateUserExists(updateReqVO.getId());
        // 更新
        UmsUserDO updateObj = BeanUtils.toBean(updateReqVO, UmsUserDO.class);
        userMapper.updateById(updateObj);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteUser(Long id) {
        // 校验存在
        validateUserExists(id);
        // 删除
        userMapper.deleteById(id);
    }

    private void validateUserExists(Long id) {
        if (userMapper.selectById(id) == null) {
            throw exception(DATA_NOT_FOUND);
        }
    }

    @Override
    public UmsUserDO getUser(Long id) {
        return userMapper.selectById(id);
    }

    @Override
    public PageResult<UmsUserDO> getUserPage(UmsUserPageReqVO pageReqVO) {
        return userMapper.selectPage(pageReqVO);
    }

}
